package LOGIN;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.example.xfengshopping.MainActivity;
import com.example.xfengshopping.R;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import user.fragment.AccountManagement;
import utils.TokenUtils;

public class login extends AppCompatActivity {
    private static final String TAG = "LoginActivity";

    private EditText account;
    private EditText password;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private final OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        /*        if (isUserLoggedIn()) {
            navigateToMainActivity();
            return;
        }*/
        backMainListener();
        skipToAccountManagement();
        initViews();
    }
    private void backMainListener() {
        ImageView backLogin = findViewById(R.id.backMain);
        backLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(login.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void skipToAccountManagement(){
        ImageView skipToAM=findViewById(R.id.skipToManagement);
        skipToAM.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(login.this, AccountManagement.class);
                startActivity(intent);
                finish();
            }
        });
    }
    private void initViews() {
        account = findViewById(R.id.account);
        password = findViewById(R.id.Password);

        Button registerButton = findViewById(R.id.register);
        registerButton.setOnClickListener(v -> {
            startActivity(new Intent(login.this, register.class));
            finish();
        });

        Button loginButton = findViewById(R.id.login);
        loginButton.setOnClickListener(v -> attemptLogin());
    }

    private void attemptLogin() {
        String accountStr = account.getText().toString().trim();
        String passwordStr = password.getText().toString().trim();

        if (accountStr.isEmpty() || passwordStr.isEmpty()) {
            showToast("请输入账户和密码");
            return;
        }

        showToast("登录中...");
        String encryptedPwd = md5(passwordStr);
        loginUser(accountStr, encryptedPwd);
    }

    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            Log.e(TAG, "MD5加密失败", e);
            return "";
        }
    }

    private void loginUser(String loginName, String passwordMd5) {
        new Thread(() -> {
            try {
                JsonObject requestBody = new JsonObject();
                requestBody.addProperty("loginName", loginName);
                requestBody.addProperty("passwordMd5", passwordMd5);

                RequestBody body = RequestBody.create(
                        JSON,
                        new Gson().toJson(requestBody)
                );

                Request request = new Request.Builder()
                        //.url("http://115.158.64.84:28019/api/v1/user/login")//校内
                        .url("http://47.99.134.126:28019/api/v1/user/login")//校外
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .addHeader("Accept", "application/json")
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    String responseBody = response.body().string();
                    JsonObject jsonResponse = new Gson().fromJson(responseBody, JsonObject.class);

                    if (response.isSuccessful()) {
                        int resultCode = jsonResponse.get("resultCode").getAsInt();
                        if (resultCode == 200) { // 根据服务器实际返回值调整
                            handleSuccessResponse(jsonResponse);
                        } else {
                            handleApiError(jsonResponse); // 重命名方法
                        }
                    } else {
                        handleHttpError(response.code(), jsonResponse);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "登录异常", e);
                showToast("登录失败: " + e.getMessage());
            }
        }).start();
    }

    // 重命名方法（原handleBusinessError）
    private void handleApiError(JsonObject response) {
        String errorMsg = response.has("message") ?
                response.get("message").getAsString() : "操作失败";
        Log.e(TAG, "API错误: " + errorMsg);
        showToast(errorMsg);
    }

    private void handleHttpError(int statusCode, JsonObject response) {
        String errorMsg = "HTTP错误: " + statusCode;
        if (response.has("message")) {
            errorMsg += " - " + response.get("message").getAsString();
        }
        Log.e(TAG, errorMsg);
        showToast(errorMsg);
    }

    private void handleSuccessResponse(JsonObject response) {
        String token = response.get("data").getAsString();
        TokenUtils.saveToken(login.this, token);
        String loginName = account.getText().toString().trim(); // 获取当前登录的账号

        // 保存 Token 和登录名到 SharedPreferences
        TokenUtils.saveToken(login.this, token);
        saveLoginNameToSharedPreferences(loginName); // 新增存储账号的方法

        runOnUiThread(() -> {
            showToast("登录成功");
            navigateToMainActivity();
        });
    }

    private void saveLoginNameToSharedPreferences(String loginName) {
        SharedPreferences sharedPreferences = getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("loginName", loginName); // 存储键为 "loginName"
        editor.apply();
    }

    private void navigateToMainActivity() {
        new Handler().post(() -> {
            Intent intent = new Intent(login.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
    }

    private void showToast(String msg) {
        runOnUiThread(() -> Toast.makeText(login.this, msg, Toast.LENGTH_SHORT).show());
    }
}